//
//  UserAccount.swift
//  MyWeibo
//
//  Created by 余丽丽 on 15/10/10.
//  Copyright © 2015年 余丽丽. All rights reserved.
/*
result = Optional(["access_token": 2.00Q77WrCZzKi_B9fea624107wEpXgB, "remind_in": 157679999, "uid": 2623139540, "expires_in": 157679999])

*/
// 用户模型
import UIKit

class UserAccount: NSObject,NSCoding{
    
    /// 用户是否登记的标记
    class var userLogon: Bool{
        return loadAccount() != nil
    }
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token:String?
    /// access_token的生命周期，单位是秒数 - 准确的数据类型是`数值`
    var expires_in:NSTimeInterval = 0 {
        didSet {
            // 将生命周期转换成过期日期
            // NSDate的init方法:public convenience init(timeIntervalSinceNow secs: NSTimeInterval)
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: NSDate?
    /// 当前授权用户的UID
    var uid:String?
    
    
    // 用户信息
    var name:String?
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    //字典转模型 用字典初始化对象
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        //设置全局用户信息
        UserAccount.userAccount = self
    }
    
    //保存归档解档的路径
    static private var accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")

    
    // 重写没有定义的key的KVC方法,{}什么都不写是为了让其失效,因为dict中共有四个参数,只定义了三个
    override func setValue(value: AnyObject?, forUndefinedKey key: String){}
 
    override var description:String{
        let properties = ["access_token", "expires_in", "uid","name","avatar_large"]
//        print(UserAccount.accountPath)
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    // MARK: - 加载用户信息
    // 加载用户信息
    func loadUserInfo(finished:(error: NSError?)->()){
        NetworkTools.sharedTools.loadUserInfo(uid!){(result,error) -> () in
            if error != nil{
                finished(error: error)
                return
            }
            
            //设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            //保存用户信息
            self.saveAccout()
            
            //完成回调
            finished(error: nil)
            
        
        }
    
    }
    
    // 判断token是否存在或者过期
    private static var userAccount:UserAccount?
    class func loadAccount() -> UserAccount? {
        //先判断账户是否存在
        if userAccount == nil {
            //解档,如果没有保存过,解档可能仍然是nil
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        }
        
        //判断是否过期
        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{
            userAccount = nil
        }
        
        return userAccount
    }
    
    // 保存用户信息
    private func saveAccout(){
        //归档

        NSKeyedArchiver.archiveRootObject(self, toFile:UserAccount.accountPath)
        print(UserAccount.accountPath)
    }
    
    
    // MARK: NSCoding
    // 归档 -> 保存 将自定义的对象转换成二进制数据
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    // 解档 -> 恢复 将二进制数据从磁盘恢复成自定义对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}
